<?php
/*
 * autor: Juan Manuel Rodriguez
 * */
require_once('constantesMvial.php'); 

$flagPays = false;
$flagPay = false;
$flagPayment = false;
$orderAndMoney=array();
$currentPayOrder=0;

function doPost($url, $post = null)
{
	$context = array();	
	if (is_array($post))
	{
	ksort($post);	
	$context['http'] = array
	(
		'method' => 'GET',
		'content' => http_build_query($post, '', '&'),
	);
	}
	return file_get_contents($url, false, stream_context_create($context));
}

/*XML PARSE AUX**/
function startElement($parser, $name, $attrs)
{
    global $flagPays,$flagPay,$flagPayment,$orderAndMoney, $currentPayOrder;

    if($name=="PAYS"){
		$flagPays=true;
    }else if($flagPays && $name=="PAY"){
		$flagPay=true;
		$currentPayOrder=$attrs["TRX_ID"];	
    }else if($flagPay && $name=="TRX_PAYMENT"){
		$flagPayment = true;
    }
}

function endElement($parser, $name) 
{
    global $flagPays,$flagPay,$flagPayment,$orderAndMoney, $currentPayOrder;

    if($flagPay && $name=="TRX_PAYMENT"){
		$flagPayment = false;
    }
    if($name=="PAYS"){
		$flagPays=false;
    }if($flagPays && $name=="PAY"){
		$flagPay=false;	
    }
}

function characterData($parser, $data) 
{
   global $flagPays,$flagPay,$flagPayment,$orderAndMoney, $currentPayOrder;

   if($flagPay && $flagPayment){
   	if($currentPayOrder!=0){
		$orderAndMoney[$currentPayOrder]=$data;
   	}
   }
}
/*XML PARSE AUX**/
/*
 * Los parametros deben ser strings con el siguiiente formato: yyyymmdd
 * Devuelve un array con numero de ordern y dinero de esa orden.
 * Si hay algun error agrega un campo "ERROR" en el array con dicho error
 * */
function getDineroMailData($startDate,$endDate){
	 
	global $flagPays,$flagPay,$flagPayment,$orderAndMoney, $currentPayOrder;
	
	$xml_parser = xml_parser_create();
	$myPostData = array(  'Email'=>DINEROMAIL_USER_MAIL,
			'Acount'=>DINEROMAIL_ACOUNT,
			'Pin'=>DINEROMAIL_PIN,
			'StartDate'=>$startDate,
			'EndDate'=>$endDate,
			'XML'=>'1');
	$xmlStream=doPost(DINEROMAIL_URL_CHECK,$myPostData);
	//PARSE XML
	xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
	xml_set_element_handler($xml_parser, "startElement", "endElement");
	xml_set_character_data_handler($xml_parser, "characterData");
	if (!xml_parse($xml_parser, $xmlStream)) {
	       $orderAndMoney["ERROR"]="Imposible conectar con el servidor de dinero mail o parsear el resultado de la consulta";
	}
	xml_parser_free($xml_parser);
	//END XML

	return $orderAndMoney;
}

?>
